package com.lg.cms.controller.admin.article;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.controller.admin.wlt.WltController;
import com.lg.cms.entity.Article;
import com.lg.cms.entity.Category;
import com.lg.cms.entity.SuperUser;
import com.lg.cms.service.ArticleService;
import com.lg.cms.service.ArticleTypeService;
import com.lg.cms.service.CategoryService;
import com.lg.cms.service.TagsService;
import com.lg.cms.utils.SubjectUtil;
import com.lg.cms.utils.UploadFileUtil;
import com.lg.cms.vo.LayerTableVO;
import com.lg.cms.vo.admin.SuperArticleVO;
import com.lg.cms.vo.admin.SuperUserVO;
import com.lg.cms.vo.admin.addArticleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Description:文章
 * @author:MaShucahng
 * @date: 2020/9/26 18:23
 */
@Controller
@RequestMapping("/admin/wlt")
@Api(tags = "文章管理")
public class ImageController {

    @Autowired
    CategoryService categoryService;
    @Resource
    UploadFileUtil uploadFileUtil;
    @Autowired
    ArticleService articleService;
    @Autowired
    ArticleTypeService articleTypeService;
    @Autowired
    TagsService tagsService;
//    @Resource
//    UploadFileUtil uploadFileUtil;

//    @GetMapping("/get")
//    public String add() {
//        return "/admin/wlt-test/article";
//    }

    @GetMapping("/get")
    public String addController(){

        return "/admin/wlt-test/article";

    }




    @GetMapping("/lists")
    public String address(Model model, HttpServletRequest request) {
        model.addAttribute("request", request);
        model.addAttribute("articleTypeList", articleTypeService.list());
        return "/admin/wlt-test/articleList";
    }

    @GetMapping("video")
    public String video() {
        return "/admin/wlt-test/editVideo";
    }

    @GetMapping("audio")
    public String audio() {
        return "/admin/wlt-test/editAudio";
    }

    @GetMapping("picture")
    public String picture() {
        return "admin/wlt-test/editPicture";
    }


    /**
     * 文章新增页
     *
     * @param model
     * @return
     */
    @GetMapping("/add_article")
    public String addArticle(Model model, HttpServletRequest request) {
        model.addAttribute("request", request);
        model.addAttribute("user", SubjectUtil.getSuperUser());
        model.addAttribute("categoryList", categoryService.list(new QueryWrapper<Category>().orderByAsc("sort")));
        model.addAttribute("articleTypeList", articleTypeService.list());
        model.addAttribute("tagsList", tagsService.list());
        return "/admin/wlt-test/article";
    }


//    public R<?> updateArticle(HttpServletRequest request,Article article){
//
//
//
//    }




    /**
     * 修改文章
     * @param model
     * @param request
     * @return
     */
    @PostMapping("/update_article")
    @ResponseBody
    @ApiOperation("修改文章")
    public String updateArticle(Model model, HttpServletRequest request) {
        Article article=new Article();

        //获取作者
        String author = request.getParameter("articleId");
        System.out.println("0+++++++++++++"+author);
        article.setAuthor(author);
        //获取类型id
        Integer article_type_id = Integer.parseInt(request.getParameter("articleClass"));
        article.setArticleTypeId(article_type_id);
        //获得id
        Integer id=Integer.parseInt(request.getParameter("id"));
        article.setId(id);
        //获得栏目
        Integer categoryId=Integer.parseInt(request.getParameter("articleB"));
        article.setCategoryId(categoryId);
        //开启评论
        boolean  comment=Boolean.valueOf(request.getParameter("articleP"));
        article.setComment(comment);
        String comments=request.getParameter("articleP");
        //封面图片
        String coverImage=request.getParameter("coverImage");
        article.setCoverImage(coverImage);
        //推荐
        boolean  recommended=Boolean.valueOf(request.getParameter("articleT"));
        String recommendeds = request.getParameter("articleT");
        article.setRecommended(recommended);
        System.out.println("        System.out.println(recommended);\n"+recommended);
        //状态
        boolean state=Boolean.valueOf(request.getParameter("articleState"));
        article.setState(state);
        System.out.println(state);
        //是否置顶
        boolean  top=Boolean.valueOf(request.getParameter("articleZ"));
        String tops = request.getParameter("articleZ");
        article.setTop(top);
        //标题
        String title=request.getParameter("articleName");
        article.setTitle(title);
        //文章介绍
        String description=request.getParameter("articleJ");
        article.setDescription(description);
        //纯文本，富文本
        String content = request.getParameter("content");
        article.setContent(content);
        String markdown_content = request.getParameter("markdown_content");
        article.setMarkdownContent(markdown_content);
        Set<Integer> tagsIdSet = new HashSet<>();
        System.out.println();

        return articleService.updateArticle(article,tagsIdSet);
    }


    /***
     * 查看文章
     *
     */
    @GetMapping("/selectarticle/{id}")
    @ResponseBody
    public R<?> getById(@PathVariable("id") Integer id){

        List<addArticleVO> superUser=articleService.selectArticle(id) ;

        if(superUser == null){
            System.out.println("为空返回");
            return R.failed("此超级用户不存在");
        }

        addArticleVO ass=new addArticleVO();
        for (addArticleVO a:superUser
             ) {
            ass.setId(a.getId());
            ass.setAuthor(a.getAuthor());
            ass.setArticleType(a.getArticleType());
            ass.setCategory(a.getCategory());
            ass.setCategoryId(a.getCategoryId());
            ass.setArticleTypeId(a.getArticleTypeId());
            ass.setComments(a.getComments());
            ass.setComment(a.getComment());
            ass.setContent(a.getContent());
            ass.setCoverImage(a.getCoverImage());
            ass.setCreateTime(a.getCreateTime());
            ass.setDescription(a.getDescription());
            ass.setFileTypeId(a.getFileTypeId());
            ass.setMarkdownContent(a.getMarkdownContent());
            ass.setRecommendeds(a.getRecommendeds());
            ass.setRecommended(a.getRecommended());
            ass.setStates(a.getStates());
            ass.setState(a.getState());
            ass.setSuperUserId(a.getSuperUserId());
            ass.setTitle(a.getTitle());
            ass.setTop(a.getTop());
            ass.setTops(a.getTops());
        }


        //被加密过的数据不能发送给前端, 不提供修改信息中直接修改密码操作



        return R.ok(ass);
    }
    /***
     *
     * 显示文章列表
     *
     */

    @GetMapping("/list")
    @ResponseBody

    public LayerTableVO list(Model model, HttpServletRequest request) {
//        model.addAttribute("request", request);
//        model.addAttribute("user", SubjectUtil.getSuperUser());
//        QueryWrapper<Article> wrapper = new QueryWrapper<>();
//        model.addAttribute("request", request);
        model.addAttribute("request", request);

        LayerTableVO lt = new LayerTableVO();
        //获取作者
        String author = request.getParameter("author");
        //  获取类型id
        String article_type_id = request.getParameter("articleTypeId");
        System.out.println("article_type_id"+article_type_id);

        //获取发布状态
        String state = request.getParameter("state");
        System.out.println("state:::"+state+":::author"+author+":::article_type_id:::"+article_type_id);
        if (state!=null&&state!=""){
            if (state.equals("是")){


                state="true";
            }else if (state.equals("否")){

                state="false";
            }

        }



//        System.out.println("article_type_id    :"+article_type_id);
        //获取分页
        Integer tagsId = Integer.parseInt(request.getParameter("page"));
        Integer pageNum = Integer.parseInt(request.getParameter("limit"));
        //如果都不为空
        if (author != null && article_type_id != null && state != null&&author != "" && article_type_id !="" && state !="") {
            System.out.println("都不爲空");
            Integer article_type_ids = Integer.parseInt(article_type_id);
            boolean states = Boolean.valueOf(state);
            lt = articleService.fuzzyAllList(author, article_type_ids, states,tagsId, pageNum);

        } else

            //如果只有作者不为空
            if ((author != null && article_type_id == null && state == null)||(author != "" && article_type_id == "" && state == "")) {
                System.out.println("作者不爲空");
                lt = articleService.fuzzyAllList(author,tagsId, pageNum);



            } else
                //如果只有类型id不为空
                if ((author == null && article_type_id != null && state == null)||(author == "" && article_type_id != "" && state == "")) {

                    Integer article_type_ids = Integer.parseInt(article_type_id);
                    lt = articleService.fuzzyAllList(article_type_ids,tagsId, pageNum);
                    System.out.println("id不爲空");


                } else
                    //如果只有发布状态不为空
                    if ((author == null && article_type_id == null && state != null)||(author == "" && article_type_id == "" && state != "")) {
                        System.out.println("state:::"+state+":::author"+author+":::article_type_id:::"+article_type_id);
                        boolean states = Boolean.valueOf(state);




                        lt = articleService.fuzzyAllList(states,tagsId, pageNum);
                    } else
                        //如果类型和发布状态不为空
                        if ((author == null && article_type_id != null && state != null)||(author == "" && article_type_id != "" && state !="")) {

                            Integer article_type_ids = Integer.parseInt(article_type_id);
                            boolean states = Boolean.valueOf(state);
                            lt = articleService.fuzzyAllList(article_type_ids, states,tagsId, pageNum);

                        } else
                            //如果作者和发布状态不为空
                            if ((author != null && article_type_id == null && state != null)||(author != "" && article_type_id == "" && state != "")) {


                                boolean states = Boolean.valueOf(state);
                                lt = articleService.fuzzyAllList(author, states,tagsId, pageNum);

                            } else
                                //如果作者和类型不为空
                                if ((author != null && article_type_id != null && state == null)||(author != "" && article_type_id != "" && state == "")) {

                                    Integer article_type_ids = Integer.parseInt(article_type_id);
                                    lt = articleService.fuzzyAllList(author, article_type_ids,tagsId, pageNum);

                                }else{

                                    lt=articleService.findByPage(tagsId, pageNum);


                                }








        return lt;
    }

    /**
     * 根据文章id获取文章标签列表
     * @param articleId
     *
     * @return
     */
    @GetMapping("/get_tags")
    @ResponseBody
    public R<?> getTags(Integer articleId){
        if(articleId == null){
            return R.failed("文章id为空");
        }
        return R.ok(articleService.getTagsListByArticleId(articleId));
    }






    /**
     * layui接受的数据格式如下：
     * response: { //定义后端 json 格式，详细参见官方文档
     *             code: 0,
     *             msg: "",
     *             count: 1000,
     *             data: []
     *           }
     * @return
     */



    @PostMapping("/add_article")
    @ResponseBody
    @ApiOperation("新增文章")
    public R<?> addArticle(HttpServletRequest request, Article article) {
//        System.out.println("request"+request);
        //添加类型：文章 1，图片2，视频音频3
        String ss= request.getParameter("type");
        article.setFileTypeId(Integer.parseInt(ss));
        //超级用户表实体类id
        SuperUser user = SubjectUtil.getSuperUser();
        article.setSuperUserId(user.getId());
        //添加文章名称
        article.setTitle(request.getParameter("b"));
        System.out.println(request.getParameter("b"));
        //文章发布状态
        article.setState(true);
        //文章作者
        article.setAuthor(user.getUsername());
        //开启评论
       String aa= request.getParameter("h");
       if (aa.equals("是"))
           article.setComment(true);
        else
           article.setComment(false);
        //是否置顶
        String top=request.getParameter("g");
        if (top.equals("是"))
            article.setTop(true);
        else
            article.setTop(false);
        //是否推荐
        String recommended=request.getParameter("f");
        if (recommended.equals("是"))
            article.setRecommended(true);
        else
            article.setRecommended(false);
        //获得富文本
        if (Integer.parseInt(ss)==1)
        article.setDescription(request.getParameter("c"));
        //文章栏目
        article.setCategoryId(1);
        //文章概要
        article.setContent(request.getParameter("i"));
        //判断是保存还是发布
        String issue=request.getParameter("j");//发布
        String save=request.getParameter("k");//保存
        if (issue!=null)
            article.setState(true);
        else if (save!=null)
            article.setState(false);

        //添加文章多对多表文章类型表
        article.setArticleTypeId(articleTypeService.getArticleTypeMap().get("article"));
        Set<Integer> tagsIdSet = new HashSet<>();
        String[] tagsIdArray = request.getParameterValues("e[]");
//        if (tagsIdArray != null) {
//            Arrays.asList(tagsIdArray).forEach(v -> tagsIdSet.add(Integer.parseInt(v)));
//        }
        return articleService.addArticle(article, tagsIdSet);

    }





//    @PostMapping("/upload")
//    @ResponseBody
//    public Article upload(MultipartFile upload){
//
//        R r = uploadFileUtil.uploadLocal(upload);
//        r.getCode();
//        r.getMsg();
//        r.getData();
//

//
//        if(r.getCode() == 0){
//            return new Article(1, (String)r.getData(), (String)r.getData(), null);
//        }else{
//            return new Article(0, null, null, r.getMsg());
//        }

//
//    }
//
//    /**
//     * Created by wangchen on 2019/10/16 15:18
//     * Description: 上传图片返回信息 CKEditor需要返回json信息
//     * uploaded 在上传成功时可以设置为1 失败为 0
//     * fileName 为文件名
//     * url 为文件的实际访问路径
//     */
//    @Data
//    @AllArgsConstructor
//    @NoArgsConstructor
//    private class ImageUploadVo {
//        private int uploaded;
//        private String fileName;
//        private String url;
//        private String msg;
//    }
//
//    @PostMapping("/add_article")
//    @ResponseBody
//    @ApiOperation("新增文章")
//    public R<?> addArticle(HttpServletRequest request, Article article) {
//        //获得超级用户表实体类id
//        SuperUser user = SubjectUtil.getSuperUser();
//        article.setSuperUserId(user.getId());
//        //获得文章发布状态
//        article.setState(true);
//        //获得文章类型
//        article.setArticleTypeId(articleTypeService.getArticleTypeMap().get("article"));
//
//        Set<Integer> tagsIdSet = new HashSet<>();
//        //获取前端tagsIds数据
//        String[] tagsIdArray = request.getParameterValues("tagsIds[]");
//        if (tagsIdArray != null) {
//            Arrays.asList(tagsIdArray).forEach(v -> tagsIdSet.add(Integer.parseInt(v)));
//        }
//        System.out.println(article);
//        System.out.println(tagsIdSet);
//        return articleService.addArticle(article, tagsIdSet);
//
//    }


//    //Freemaker的核心配置类，用于动态生成模板对象
//    //在SpringBoot IOC容器初始化的时候，自动Configuration就被实例化
////    @Resource
////    private Configuration freemarkerConfig;
//
//    @RequestMapping("/article/images")
//    public String file(ModelMap map) {
//
////        map.addAttribute("host", "Spring test");
//
//        return "article/iamge";
//    }
//
//    @RequestMapping("/article/shows")
//    public String files(ModelMap map) {
//
////        map.addAttribute("host", "Spring test");
//
//        return "article/show";
//    }
//
//
//
//    @Autowired
//    private ArticleService articleService;
//    private Article article=new Article();
//
//
//    @RequestMapping("/uploads")
//    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
//        byte[] bytes = file.getBytes();
//        article.setCoverImage(bytes);
//        article.setTitle(file.getOriginalFilename());
//        article.setFileTypeId(1);
//        articleService.addPhoto(article);
//        return "article/show";
//
//
//
//    }
//    @RequestMapping("/getPhotos")
//    public String getImage(HttpServletResponse response) throws IOException {
//        Article articles = articleService.getPhotoById(1);
//        byte[] photo1 = article.getCoverImage();
//        ServletOutputStream os = response.getOutputStream();
//        os.write(photo1);
//        os.close();
//        return "";
//    }
//
//    @ResponseBody
//    @GetMapping("/getImage")
//    public void getImage(Long orderId,HttpServletResponse response){
//        try {
//            Article articles = articleService.getPhotoById(1);
//
//            byte[] image = articles.getCoverImage();
//
//            response.setContentType("image/jpeg");
//            response.setCharacterEncoding("UTF-8");
//            OutputStream outputSream = response.getOutputStream();
//            InputStream in = new ByteArrayInputStream(image);
//            int len = 0;
//            byte[] buf = new byte[1024];
//            while ((len = in.read(buf, 0, 1024)) != -1) {
//                outputSream.write(buf, 0, len);
//            }
//
//            outputSream.close();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//
//    }
//
//
////    @Autowired
////    SaveConfigService saveConfigService;
//
//
//}
    /***
     * 通过id单文章删除
     *
     */
    @PostMapping("/deleteArtile")
    @ResponseBody
    @ApiOperation("删除文章")
    public String dieleteArtile(Model model,HttpServletRequest request){
        Integer  id=Integer.parseInt(request.getParameter("id"));
        if (articleService.deleteArticle(id)==1)
            return "删除成功";
        else
            return"删除失败";


    }

    /**
     * 通过id批量删除
     *
     */
    @PostMapping("/alldeleteArtile")
    @ResponseBody
    @ApiOperation("批量删除文章")
    public String alldeleteArtile(Model model,HttpServletRequest request) {
        //获取批量删除id
        String [] Allid = request.getParameterValues("ids[]");

        //字符串数组转换成int数组（1.8可用）
        int [] li=Arrays.asList(Allid).stream().mapToInt(Integer::parseInt).toArray();
        if (articleService.AlldeleteArticle(li) == 1)
            return "删除成功";
        else
            return "删除失败";

    }


//    /**
//     * 显示类型复选框
//     */
//    @GetMapping("/Binding_typeArticle")
//    @ResponseBody
//
//    public LayerTableVO Binding_typeArticle(Model model, HttpServletRequest request) {
//        return   articleService.Binding_typeArticle();
//
//    }

}